from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User as AuthUser

class Announcement(models.Model):
    """
    公告模型
    """
    title = models.CharField(max_length=255, verbose_name="公告标题")  # 公告标题
    content = models.TextField(verbose_name="公告内容")  # 公告内容
    is_visible = models.BooleanField(default=True, verbose_name="是否可见")  # 是否可见
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")  # 创建时间
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")  # 更新时间
    published_at = models.DateTimeField(default=timezone.now, verbose_name="发布时间")  # 发布时间

    class Meta:
        db_table = 'announcement'
        verbose_name = "公告"
        verbose_name_plural = "公告管理"
        ordering = ['-published_at']  # 按发布时间倒序排列

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        """
        自定义保存方法，确保在保存时更新时间戳
        """
        if not self.id:  # 如果是新创建的对象
            self.created_at = timezone.now()
        self.updated_at = timezone.now()
        super().save(*args, **kwargs)

    def visible_status(self):
        """
        返回是否可见的状态描述
        """
        return "可见" if self.is_visible else "不可见"

    visible_status.short_description = "可见状态"


class Book(models.Model):
    title = models.CharField(max_length=255, verbose_name="书名")
    author = models.CharField(max_length=255, verbose_name="作者")
    category = models.CharField(max_length=255, verbose_name="类别")
    publish_date = models.DateField(verbose_name="出版日期", null=True, blank=True)
    isbn = models.CharField(max_length=13, unique=True, verbose_name="ISBN")
    description = models.TextField(verbose_name="简介", null=True, blank=True)

    class Meta:
        db_table = 'book'
        verbose_name = "书本"
        verbose_name_plural = "书本"
        ordering = ['-id']  # 按发布时间倒序排列

    def __str__(self):
        return self.title


class UserProfile(models.Model):
    user = models.OneToOneField(AuthUser, on_delete=models.CASCADE)
    role = models.CharField(max_length=255, choices=[('admin', '图书管理员'), ('user', '读者'),('root', '系统管理员')], default='user', verbose_name="角色")

    class Meta:
        db_table = 'user'
        verbose_name = "用户"
        verbose_name_plural = "用户"
        ordering = ['-id']  # 按发布时间倒序排列

    def __str__(self):
        return self.user.username

class BorrowRecord(models.Model):
    user = models.ForeignKey(AuthUser, related_name='borrow_records', on_delete=models.CASCADE, verbose_name="用户")
    book = models.ForeignKey('Book', related_name='borrow_records', on_delete=models.CASCADE, verbose_name="图书")
    borrow_date = models.DateTimeField(auto_now_add=True, verbose_name="借阅日期")
    return_date = models.DateTimeField(null=True, blank=True, verbose_name="归还日期")

    class Meta:
        db_table = 'borrow_record'
        verbose_name = "借阅记录"
        verbose_name_plural = "借阅记录"
        ordering = ['-borrow_date']

    def __str__(self):
        return f"{self.user.username} - {self.book.title}"

class Rating(models.Model):
    user = models.ForeignKey('auth.User', related_name='ratings', on_delete=models.CASCADE, verbose_name="用户")
    book = models.ForeignKey(Book, related_name='ratings', on_delete=models.CASCADE, verbose_name="图书")
    score = models.PositiveIntegerField(choices=[(i, i) for i in range(1, 6)], verbose_name="评分")  # 评分范围1-5

    class Meta:
        db_table = 'rating'
        verbose_name = "评分"
        verbose_name_plural = "评分"
        ordering = ['-id']  # 按借阅日期倒序排列
        unique_together = ('user', 'book')  # 确保一个用户对一本书只能评分一次

    def __str__(self):
        return f"{self.user.username} rated {self.book.title} with {self.score} stars"